package com.itheima.restkeeper.handler.wechat.operators.baisc;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.itheima.restkeeper.enums.TradingEnum;
import com.itheima.restkeeper.exception.ProjectException;
import com.itheima.restkeeper.handler.wechat.client.Config;
import com.itheima.restkeeper.handler.wechat.client.WechatPayHttpClient;
import com.itheima.restkeeper.handler.wechat.response.RefundResponse;
import com.itheima.restkeeper.utils.ExceptionsUtil;
import lombok.Data;
import lombok.extern.log4j.Log4j2;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * @ClassName Refund.java
 * @Description TODO
 */
@Data
@Log4j2
public class Refund extends SystemParams {

    public Refund(Config config) {
        super(config);
    }

    /***
     * @description 统一收单交易退款接口【native和jsapi通用】
     * @param outTradeNo 发起支付传递的交易单号
     * @param amount 退款金额
     * @param outRefundNo 商户系统内部的退款单号，商户系统内部唯一，只能是数字、大小写字母_-|*@ ，同一退款单号多次请求只退一笔
     * @param total 原订单金额
     * @return
     */
    public RefundResponse refund(String outTradeNo, String amount,
                                 String outRefundNo, String total) throws ProjectException {
        //请求地址
        String uri = "/v3/refund/domestic/refunds";
        WechatPayHttpClient httpClient = WechatPayHttpClient.builder()
                .mchId(mchId)
                .mchSerialNo(mchSerialNo)
                .apiV3Key(apiV3Key)
                .privateKey(privateKey)
                .domain(domain + uri)
                .build();
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode bodyParams = objectMapper.createObjectNode();
        BigDecimal bigDecimal = new BigDecimal(amount);
        BigDecimal multiply = bigDecimal.multiply(new BigDecimal(100));
        BigDecimal bigDecimalTotal = new BigDecimal(total);
        BigDecimal multiplyTotal = bigDecimalTotal.multiply(new BigDecimal(100));
        bodyParams.put("out_refund_no", outRefundNo)
                .put("out_trade_no", outTradeNo);
        bodyParams.putObject("amount")
                .put("refund", multiply.intValue())
                .put("total", multiplyTotal.intValue())
                .put("currency", "CNY");
        String body = null;
        try {
            body = httpClient.doPost(bodyParams);
        } catch (IOException e) {
            log.error("微信支付：refund，发生异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(TradingEnum.NATIVE_REFUND_FAIL);
        }
        RefundResponse refundResponse = JSONObject.parseObject(body, RefundResponse.class);
        refundResponse.setCode("200");
        return refundResponse;
    }

}
